package com.example.backend.domain.entity;

import com.example.backend.domain.enums.FileType;
import com.example.backend.domain.enums.FileStatus;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.Instant;

/**
 * 文件实体
 */
@Entity
@Table(name = "files")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class File {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, length = 255)
    private String fileName;
    
    @Column(nullable = false, length = 500)
    private String originalFileName;
    
    @Column(nullable = false, length = 1000)
    private String filePath;
    
    @Column(nullable = false)
    private Long fileSize;
    
    @Column(nullable = false, length = 100)
    private String mimeType;
    
    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    private FileType fileType;
    
    @Enumerated(EnumType.STRING)
    @Column(nullable = false)
    @Builder.Default
    private FileStatus status = FileStatus.ACTIVE;
    
    @Column(length = 500)
    private String description;
    
    @Column(length = 1000)
    private String tags;
    
    @Column(nullable = false)
    private Long uploadedBy;
    
    @Column
    private Long ticketId;
    
    @Column
    private Long commentId;
    
    @Column(length = 32)
    private String fileHash;
    
    @Column(length = 1000)
    private String metadata;
    
    @Column
    private Integer downloadCount;
    
    @Column
    private Instant lastAccessedAt;
    
    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Instant createdAt;
    
    @UpdateTimestamp
    @Column(nullable = false)
    private Instant updatedAt;
    
    @PrePersist
    protected void onCreate() {
        if (downloadCount == null) {
            downloadCount = 0;
        }
        if (status == null) {
            status = FileStatus.ACTIVE;
        }
    }
    
    @PreUpdate
    protected void onUpdate() {
        updatedAt = Instant.now();
    }
}
